<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>获取任意元素与页面的上左边距</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }

        .content {
            position: relative;
            margin: 50px;
            width: 300px;
            height: 200px;
            border: 20px solid #00f;
        }

        .box {
            width: 200px;
            height: 100px;
            margin: 30px;
            padding: 20px;
            background-color: #ff9000;
        }

        .inner {
            width: 50px;
            height: 50px;
            margin: 10px;
            background-color: #0f0;
        }
    </style>
</head>
<body>

    <div class="content">
        <div class="box">
            <div class="inner"></div>
        </div>
    </div>
    
    <script type="text/javascript">
        var content = document.querySelector(".content"),
            box = document.querySelector(".box"),
            inner = document.querySelector(".inner");

        // box与页面的上边距 = box与它的offsetParent的内容区的上边距 + 它的offsetParent的上边框的宽度 + 它的offsetParent与页面的上边距
        // inner与页面的上边距 = inner与它的offsetParent的内容区的上边距 + 它的offsetParent的上边框的宽度 + 它的offsetParent与页面的上边距
        // 元素的offsetParent是body，那么直接返回 offsetTop

        console.log(getDistance(content)); // { top: 50, left: 50 }
        console.log(getDistance(box)); // { top: 100, left: 100 }
        console.log(getDistance(inner)); // { top: 130, left: 130 }

        

        // 获取任意元素到页面上左边距的递归函数
        function getDistance(ele){
            if(ele.offsetParent == document.body){
                return {
                    top: ele.offsetTop,
                    left: ele.offsetLeft
                }
            }
            var op = ele.offsetParent;
            var opDistance = getDistance(op);
            return {
                top: ele.offsetTop + op.clientTop + opDistance.top,
                left: ele.offsetLeft + op.clientLeft + opDistance.left
            }
        }
    </script>
</body>
</html>